package com.huluobo.a2206douyindemo.login;

import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.huluobo.base.bean.UserBeanResult;
import com.huluobo.base.mvvm.BaseViewModel;
import com.huluobo.base.net.Const;

import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by LC on 2024/8/15.
 */
public class LoginViewModel extends BaseViewModel<LoginRepo> {

    //成功的回调
    MutableLiveData<UserBeanResult> loginSuccess = new MutableLiveData<>();
    //失败的回调
    MutableLiveData<String> loginFailed = new MutableLiveData<>();

    public void login(String username, String password) {
        //封装参数,因为请求需要的是一个body,但是能拿到的是2个String
        //生成map,保存键值对
        //所有的键都在接口文档中
        Map<String, String> map = new HashMap<>();
        map.put(Const.PARAM_USERNAME, username);
        map.put(Const.PARAM_PASSWORD, password);

        //把map转换为一个json,服务器只接收json类型的body
        String json = new Gson().toJson(map);
        //把json分装为body
        RequestBody body = RequestBody.create(MediaType.parse(Const.MEDIA_TYPE), json);
        //通过repo发起请求,传递成功失败和body
        repo.login(body, loginSuccess, loginFailed);
    }

    @Override
    protected LoginRepo createRepo() {
        return new LoginRepo();
    }
}
